package com.liujiaqi.service.impl;

import com.liujiaqi.mapper.DeptMapper;
import com.liujiaqi.mapper.EmpMapper;
import com.liujiaqi.pojo.Dept;
import com.liujiaqi.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService{

  @Autowired
  private DeptMapper deptMapper;

  @Autowired
  private EmpMapper empMapper;

  @Override
  public List<Dept> list() {
    return deptMapper.list();
  }

  @Transactional(rollbackFor = Exception.class) // spring事务管理
  @Override
  public void delete(Integer id) throws Exception {
    deptMapper.deleteById(id); // 根据ID删除部门数据

    // 模拟抛出异常
    int i = 1/0;

    if(true) {
      throw new Exception("出错了...");
    }

    empMapper.deleteByDeptId(id); // 根据部门ID删除该部门下的员工
  }

  @Override
  public void add(Dept dept) {
    dept.setCreateTime(LocalDateTime.now());
    dept.setUpdateTime(LocalDateTime.now());
    deptMapper.insert(dept);
  }

  @Override
  public Dept search(Integer id) {
    // 模拟抛出异常
    // int i = 1/0;
    List<Dept> deptList = deptMapper.selectById(id);
    return deptList.get(0);
  }

  @Override
  public void update(Integer id, String name) {
    deptMapper.update(id, name);
  }
}
